package com.lajiaomian.springbootruijiwaimai.filter;

import com.alibaba.fastjson.JSON;
import com.lajiaomian.springbootruijiwaimai.common.BaseContext;
import com.lajiaomian.springbootruijiwaimai.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lajiaomian
 * @create 2022-08-11-17:24
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将request和response强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //1.获取本次请求的uri
        String requestURI = request.getRequestURI();
        log.info("本次请求的URI：{}",requestURI);
        //定义不需要处理的请求
        String urls[] = new String[]{
          "/employee/login","/employee/logout","/backend/**","/front/**","/user/login","/user/sendMsg"
        };
        //2.判断本次请求是否需要处理
        boolean result = check(urls, requestURI);
        // 3.如果不需要处理，则直接方向放行
        if (result==true){
            filterChain.doFilter(request,response);
//            log.info("本次请求无需处理：{}",requestURI);
            return;
        }
        //4.1（后台用户）判断登录状态，如果已登录，则直接放行
        Long employee = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrId(employee);
        if (employee!=null){
            filterChain.doFilter(request,response);
//            log.info("用户已登录id为:{}已放行" ,employee);
            return;
        }
        //4.2（前台用户）判断登录状态，如果已登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        BaseContext.setCurrId(userId);
        if (userId!=null){
            filterChain.doFilter(request,response);
//            log.info("用户已登录id为:{}已放行" ,employee);
            return;
        }
        //5.如果未登录则返回未登录结果
        //进行拦截
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("此次请求被拦截：{}",requestURI);
        return;
    }

    public boolean check(String[] urls,String URI){
        for (String url:urls) {
            boolean match = PATH_MATCHER.match(url, URI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
